package edu.zjut.sjq.service;

import edu.zjut.sjq.bean.Article;
import edu.zjut.sjq.bean.Result;
import edu.zjut.sjq.bean.User;
import edu.zjut.sjq.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * Created by sue on 2017/3/12.
 */
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private ArticleService articleService;

    // user登陆
    public Result login(User user){
        Result result=new Result();
        result.setRes(0);
        User record=userMapper.selectByName(user.getUsername());
        if (record!=null){
            if (user.getPwd().equals(record.getPwd())){
                session.setAttribute("user",record);
                result.setMsg("登陆成功");
                result.setRes(1);
            }else {
                result.setMsg("密码错误");
            }
        }else {
            // 找不到
            result.setMsg("此用户不存在");
        }
        return result;
    }

    // 注册
    public Result register(User user){
        Result result=new Result();
        result.setRes(0);
        if (user.getUsername()==null || user.getPwd()==null || user.getMailAddress()==null){
            result.setMsg("数据不完整");
            return result;
        }
        User record=userMapper.selectByName(user.getUsername());
        if (record!=null){
            result.setMsg("此用户已经存在");
        }else {
            Date date=new Date();
            user.setCreateTime(date);
            user.setRole(0);
            Integer res=userMapper.insertUser(user);
            if (res==1){
                result.setRes(1);
                session.setAttribute("user",user);
            }else {
                result.setMsg("保存失败");
            }
        }

        return result;
    }

    // 修改用户信息
    public Result updateInfo(User user){
        Result result=new Result();
        result.setRes(0);
        if (user.getId()==null){
            result.setMsg("数据不完整");
            return result;
        }
        Integer res=userMapper.updateInfo(user);
        if (res==1){
            result.setRes(1);
            result.setMsg("修改成功");
            User newUser=userMapper.selectById(user.getId());
            session.setAttribute("user",newUser);
        }else {
            result.setMsg("保存失败");
        }
        return result;
    }

    public User selectById(Integer userId){
        return userMapper.selectById(userId);
    }
}
